package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.EmployeePasswordDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传来的明文进行加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    public void saveEmployee(EmployeeDTO employeeDTO) {

        Employee employee = new Employee();

        // 将employeeDTO中的属性值复制给employee，前提是两者的属性名必须相同
        BeanUtils.copyProperties(employeeDTO, employee);

        // 单独设置employee中的属性值

        // 默认密码为123456
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(password);

        // 账号状态默认为1启用，0是禁用
        employee.setStatus(StatusConstant.ENABLE);

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());

        // TODO
//        employee.setCreateUser(10L);
//        employee.setUpdateUser(10L);
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insert(employee);
    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {

        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 启用和禁用员工账号
     * @param status
     * @param id
     */
    public void employeeStatus(Integer status, Long id) {

        if(status == StatusConstant.ENABLE) {
            status = StatusConstant.ENABLE;
        }else if(status == StatusConstant.DISABLE) {
            status = StatusConstant.DISABLE;
        }
        employeeMapper.employeeStatus(status, id);
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    public Employee getById(Long id){

        Employee employee = employeeMapper.getById(id);

        employee.setPassword("***");

        return employee;
    }

    /**
     * 修改员工信息
     * @param employeeDTO
     */
    public void update(EmployeeDTO employeeDTO){

        Employee employee = new Employee();

        BeanUtils.copyProperties(employeeDTO, employee);

        employee.setUpdateUser(BaseContext.getCurrentId());
        employee.setUpdateTime(LocalDateTime.now());

        employeeMapper.update(employee);

    }

    /**
     * 修改员工密码
     * @param employeePasswordDTO
     */
    public void editPassword(EmployeePasswordDTO employeePasswordDTO){

        employeePasswordDTO.setId(BaseContext.getCurrentId());

        // 根据员工 ID 查询数据库中的当前密码
        String password = employeeMapper.getPasswordById(employeePasswordDTO.getId());

        // 获取前端传来的明文密码
        String oldPassword = employeePasswordDTO.getOldPassword();

        if (!password.equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))) {
            //输入的原始密码错误
            throw new PasswordErrorException("输入的原始密码错误");
        }

        String newPassword = DigestUtils.md5DigestAsHex(employeePasswordDTO.getNewPassword().getBytes());



        employeeMapper.editPassword(employeePasswordDTO.getId(), newPassword);

        employeePasswordDTO.setOldPassword("******");
        employeePasswordDTO.setNewPassword("******");
    }

}
